<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <!-- 
        let arr = [
      { id: 0, name: "柯莱特大学", parent_id: -1 },
      { id: 1, name: "教育部", parent_id: 0 },
      { id: 2, name: "技术部", parent_id: 0 },
      { id: 3, name: "销售部", parent_id: 0 },
      { id: 4, name: "交付部", parent_id: 0 },
      { id: 5, name: "金山云交付部", parent_id: 4 },
      { id: 6, name: "解决方案部门", parent_id: 4 },
      { id: 7, name: "后端组", parent_id: 6 },
      { id: 8, name: "前端组", parent_id: 6 },
      { id: 9, name: "测试组2", parent_id: 6 },
    ];
    // 把这个数组变成树状结构展示出来，parent_id:-1表示根节点
   -->
  <script>
      let list = [
      { id: 0, name: "柯莱特大学", parent_id: -1 },

      { id: 1, name: "教育部", parent_id: 0 },
      { id: 2, name: "技术部", parent_id: 0 },
      { id: 3, name: "销售部", parent_id: 0 },
      { id: 4, name: "交付部", parent_id: 0 },

      { id: 5, name: "金山云交付部", parent_id: 4 },
      { id: 6, name: "解决方案部门", parent_id: 4 },

      { id: 7, name: "后端组", parent_id: 6 },
      { id: 8, name: "前端组", parent_id: 6 },
      { id: 9, name: "测试组2", parent_id: 6 },
    ];
    // 先循环出祖先级的项，再根据id与parentId，递归获得最终数据：

    let newArr = []
    list.forEach(res => {
      if (res.parent_id === -1) {
        newArr.push(res)
      }
    })
    this.transList(list, newArr)
    console.log(newArr); //新数组

    function transList (Alist, arr) {
      arr.forEach(res => {
        Alist.forEach((tes, index) => {
          if (res.id === tes.parent_id) {
            if (!res.hasOwnProperty('children')) {
              res.children = []
            }
            res.children.push(tes)
          }
        })
        if (res.hasOwnProperty('children')) {
          this.transList(list, res.children)
        }
      })
    }
    console.log(newArr, 3333, list, 333334);
</script>













    // export function transLisToTree (list, value) {
    //   const arr = []
    //